#!/usr/bin/python

import httplib, urllib, sys

def closure_compiler(code, output_info):
  params = urllib.urlencode([
    ('externs_url', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'),
    ('externs_url', 'http://www.google.com/jsapi'),
    ('js_externs', 'var google = {}; google.setOnLoadCallback = null'),
    ('js_code', code),
    ('compilation_level', 'ADVANCED_OPTIMIZATIONS'),
    ('output_format', 'text'),
    ('output_info', output_info),
    ])
  headers = { "Content-type": "application/x-www-form-urlencoded" }
  conn = httplib.HTTPConnection('closure-compiler.appspot.com')
  conn.request('POST', '/compile', params, headers)
  response = conn.getresponse()
  data = response.read()
  conn.close()
  return data

input_fn_parts = sys.argv[1].rpartition('.')
output_fn = input_fn_parts[0] + '.min.' + input_fn_parts[2]

input = open(sys.argv[1], 'r')
input_content = input.read();
input.close()

errors = closure_compiler(input_content, 'errors')

if not errors:
  output = open(output_fn, 'w')
  output.write(closure_compiler(input_content, 'compiled_code'))
  output.close()
else:
  sys.exit(errors + '\nCompile aborted')

